﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;

namespace MarginTrading.Forms
{
    public partial class EditClient : Form
    {
        private bool bEditing = false;
        private string sEditingUser = "";
        DateTime MTRegDate = DateTime.MinValue;

        public EditClient()
        {
            InitializeComponent();
        }

        public EditClient(string clientCode)
        {
            sEditingUser = clientCode;
            InitializeComponent();
            AcceptButton = buttonOK;
        }

        private void EditClient_Load(object sender, EventArgs e)
        {
            try
            {
	            AgentCollection agentCollection = AgentServices.GetAgentCollection();
	            for (int iI = 0; iI < agentCollection.Count; iI++)
	            {
	                comboBoxAgentCode.Items.Add(agentCollection[iI].Code);
	            }
	
	            AdvisorCollection advisorCollection = AdvisorServices.GetAdvisorCollection();
	            for (int iI = 0; iI < advisorCollection.Count; iI++)
	            {
	                comboBoxAdvisorCode.Items.Add(advisorCollection[iI].Code);
	            }
            }
            catch (System.Exception ex)
            {
            	
            }
            
            if (sEditingUser != "")
            {
                buttonGO.Hide();
                textBoxClientID.Text = sEditingUser;
                textBoxClientID.Enabled = false;
                bEditing = true;
                buttonGO_Click(null, null);
                checkBoxMarginClient_CheckedChanged(null, null);
                if (checkBoxMarginClient.Checked == true)
                {
                    checkBoxMarginClient.Enabled = false;
                    comboBoxAgentCode.Enabled = false;
                    textBoxAccountBalance.Enabled = false;
                }
                return;
            }

            try
            {
	            AutoCompleteStringCollection data = new AutoCompleteStringCollection();
	
	            ClientCollection clientCollection = ClientService.GetClientCollection();
	
	            for (int iI = 0; iI < clientCollection.Count; iI++)
	            {
	                data.Add(clientCollection[iI].Code);
	            }
	
	            textBoxClientID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
	            textBoxClientID.AutoCompleteSource = AutoCompleteSource.CustomSource;
	            textBoxClientID.AutoCompleteCustomSource = data;
            }
            catch (System.Exception ex)
            {
            	
            }

            EnableControls(false);
        }


        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (validateInputs() == false)
            {
                return;
            }

            Client client = new Client();
            client.Code = sEditingUser;
            client.Title = textBoxTitle.Text;
            client.Initials = textBoxInitials.Text;
            client.OtherNames = textBoxOtherNames.Text;
            client.Surname = textBoxSurname.Text;
            client.Address_1 = textBoxAddress1.Text;
            client.Address_2 = textBoxAddress2.Text;
            client.Telephone1 = textBoxTelephone.Text;
            client.Fax = textBoxFax.Text;
            client.Advisor = comboBoxAdvisorCode.Text;
            client.Agent = comboBoxAgentCode.Text;
            if (textBoxMarginLimit.Text.Length != 0)
            {
                client.MarginLimit = double.Parse(textBoxMarginLimit.Text);
            }
            if (textBoxInterestRate.Text.Length != 0)
            {
                client.InterestRate = double.Parse(textBoxInterestRate.Text);
            }

            client.RegDate = dateTimePicker1.Value.Date;
            if (checkBoxMarginClient.Checked == true)
            {
                client.MarginClient = 1;
                if (MTRegDate != DateTime.MinValue)
                {
                    //if this client has been a margin client even before editing
                    client.MTRegDate = MTRegDate;
                }
                else
                {
                    //this client is made a margin client in this edit
                    client.MTRegDate = DateTime.Today;
                }
            }
            else
            {
                client.MarginClient = 0;
                client.MTRegDate = DateTime.MinValue;
            }

            try
            {
                ClientService.Update(client);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Failed to update client information\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if ((textBoxAccountBalance.Enabled == true) && ( ! string.IsNullOrEmpty(textBoxAccountBalance.Text)))
            {
                try
                {
                    DailyTransactionsServices.AddInitialAccBal(textBoxClientID.Text, double.Parse(textBoxAccountBalance.Text), false);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Failed to add initial account balance\nError: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            MessageBox.Show("Client information updated successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (checkBoxDontClose.Checked == false)
            {
                Close();
            }
            else
            {
                textBoxClientID.Text = "";
                textBoxTitle.Text = "";
                textBoxInitials.Text = "";
                textBoxOtherNames.Text = "";
                textBoxSurname.Text = "";
                textBoxAddress1.Text = "";
                textBoxAddress2.Text = "";
                textBoxFax.Text = "";
                textBoxTelephone.Text = "";
                textBoxMarginLimit.Text = "";
                textBoxInterestRate.Text = "";
                textBoxAccountBalance.Text = "";
                checkBoxMarginClient.Checked = false;

                textBoxClientID.Focus();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private bool validateInputs()
        {
            if (textBoxClientID.Text == "")
            {
                MessageBox.Show("Enter client code", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (textBoxMarginLimit.Text != "")
            {
                double fMarginLimit = 0;
                if (double.TryParse(textBoxMarginLimit.Text, out fMarginLimit) == false)
                {
                    MessageBox.Show("Invalid margin limit", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            if (textBoxInterestRate.Text != "")
            {
                double fInterestRate = 0;
                if (double.TryParse(textBoxInterestRate.Text, out fInterestRate) == false)
                {
                    MessageBox.Show("Invalid interest rate", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            if (textBoxAccountBalance.Text != "")
            {
                double fAccountBal = 0;
                if (double.TryParse(textBoxAccountBalance.Text, out fAccountBal) == false)
                {
                    MessageBox.Show("Invalid account balance", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            return true;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void buttonGO_Click(object sender, EventArgs e)
        {
            buttonGO.Focus();

            Client client = null;
            try
            {
                client = ClientService.GetClientByCode(textBoxClientID.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Invalid Client Code", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (client == null)
            {
                MessageBox.Show("Invalid Client Code", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            EnableControls(true);

            textBoxTitle.Text = client.Title;
            textBoxInitials.Text = client.Initials;
            textBoxOtherNames.Text = client.OtherNames;
            textBoxSurname.Text = client.Surname;
            textBoxAddress1.Text = client.Address_1;
            textBoxAddress2.Text = client.Address_2;
            textBoxTelephone.Text = client.Telephone1;
            textBoxFax.Text = client.Fax;
            comboBoxAdvisorCode.Text = client.Advisor;
            comboBoxAgentCode.Text = client.Agent;
            textBoxMarginLimit.Text = client.MarginLimit.ToString();
            dateTimePicker1.Value = client.RegDate;
            MTRegDate = client.MTRegDate;
            textBoxInterestRate.Text = client.InterestRate.ToString();

            if (client.MarginClient == 1)
            {
                checkBoxMarginClient.Checked = true;
                checkBoxMarginClient.Enabled = false;
                comboBoxAgentCode.Enabled = false;
                textBoxAccountBalance.Enabled = false;
            }
            else
            {
                checkBoxMarginClient.Checked = false;
            }

            bEditing = true;
            sEditingUser = textBoxClientID.Text;

            textBoxTitle.Focus();
        }

        private void EnableControls(bool bEnable)
        {
            textBoxTitle.Enabled = bEnable;
            textBoxInitials.Enabled = bEnable;
            textBoxOtherNames.Enabled = bEnable;
            textBoxSurname.Enabled = bEnable;
            textBoxAddress1.Enabled = bEnable;
            textBoxAddress2.Enabled = bEnable;
            textBoxTelephone.Enabled = bEnable;
            textBoxFax.Enabled = bEnable;
            comboBoxAdvisorCode.Enabled = bEnable;
            comboBoxAgentCode.Enabled = bEnable;
            textBoxMarginLimit.Enabled = bEnable;
            dateTimePicker1.Enabled = bEnable;
            textBoxInterestRate.Enabled = bEnable;
            checkBoxMarginClient.Enabled = bEnable;
            buttonOK.Enabled = bEnable;
            textBoxAccountBalance.Enabled = bEnable;

            if (checkBoxMarginClient.Checked == true)
            {
                checkBoxMarginClient.Enabled = false;
                comboBoxAgentCode.Enabled = false;
                textBoxAccountBalance.Enabled = false;
            }
        }

        private void ClearFields()
        {
            textBoxTitle.Text = "";
            textBoxInitials.Text = "";
            textBoxOtherNames.Text = "";
            textBoxSurname.Text = "";
            textBoxAddress1.Text = "";
            textBoxAddress2.Text = "";
            textBoxTelephone.Text = "";
            textBoxFax.Text = "";
            comboBoxAdvisorCode.Text = "";
            comboBoxAgentCode.Text = "";
            textBoxMarginLimit.Text = "";
        }

        private void textBoxClientID_TextChanged(object sender, EventArgs e)
        {
            if (bEditing)
            {
                bEditing = false;
                ClearFields();
                EnableControls(false);
            }
        }

        private void textBoxClientID_Enter(object sender, EventArgs e)
        {
            AcceptButton = buttonGO;
        }

        private void textBoxClientID_Leave(object sender, EventArgs e)
        {
            AcceptButton = buttonOK;
        }

        private void checkBoxMarginClient_CheckedChanged(object sender, EventArgs e)
        {
            textBoxMarginLimit.Enabled = checkBoxMarginClient.Checked;
            textBoxInterestRate.Enabled = checkBoxMarginClient.Checked;
            comboBoxAgentCode.Enabled = checkBoxMarginClient.Checked;
            textBoxAccountBalance.Enabled = checkBoxMarginClient.Checked;
        }

        private void comboBoxAgentCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Agent agent = AgentServices.GetAgentByCode(comboBoxAgentCode.Text);
                textBoxInterestRate.Text = agent.Interest_Rate.ToString();
            }
            catch (System.Exception ex)
            {
            }
        }

        private void textBoxAccountBalance_Enter(object sender, EventArgs e)
        {
          
        }
    }
}
